package sort;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: Hugh 阻塞队列的实现
 * @Date: 2021/4/9
 */
public class MyBlockQueue<T> {

    private final List<T> dataQueue;
    private final ReentrantLock lock;
    private final Condition isEmpty;
    private final Condition isFull;
    private Integer capCity;

    public MyBlockQueue(Integer capCity, Boolean isFair){
        dataQueue = new LinkedList<>();
        lock = new ReentrantLock(isFair);
        isEmpty = lock.newCondition();
        isFull = lock.newCondition();
        this.capCity = capCity;
    }

    public Boolean put(T t){
        lock.lock();
        try {
            while (dataQueue.size() >= capCity) {
                isFull.await();
            }
            dataQueue.add(t);
            capCity++;
            isEmpty.signalAll();
        }catch (InterruptedException e){
            System.out.println(e);
        }finally {
            lock.unlock();
        }
        return true;
    }

    public T take(){
        T res = null;
        lock.lock();
        try{
            while (dataQueue.size() <= 0) {
                isEmpty.await();
            }
            res = dataQueue.remove(0);
            capCity--;
            isFull.signal();
        }catch (InterruptedException e){
            System.out.println(e);
        }finally {
            lock.unlock();
        }
        return res;
    }
}
